package ducct.footprint.ui.adapter;

import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import ducct.footprint.R;
import ducct.footprint.entity.MyFootprint;
import ducct.footprint.ui.MyFootprintDetailActivity;
import ducct.footprint.utils.Global;
import ducct.footprint.utils.ImageLoader;

public class MyFootprintAdapter extends ArrayAdapter<MyFootprint> {
	private ImageLoader imageLoader;

	public MyFootprintAdapter(Context context, int textViewResourceId,
			List<MyFootprint> objects) {
		super(context, textViewResourceId, objects);
	}
	
	public MyFootprintAdapter(Context context, List<MyFootprint> objects) {
		this(context, 0, objects);
		imageLoader = new ImageLoader(context);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		
		if (convertView == null) {
			holder = new ViewHolder();
			
			convertView = LayoutInflater.from(getContext()).inflate(R.layout.footprint_item, null);
			holder.imgLocation = (ImageView) convertView.findViewById(R.id.imgLocation);
			holder.txtLocationName = (TextView) convertView.findViewById(R.id.txtLocationName);
			holder.txtTimestamp = (TextView) convertView.findViewById(R.id.txtTimestamp);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		// push data to UI
		myFootprint = getItem(position);
		holder.txtLocationName.setText(myFootprint.locationName);
		holder.txtTimestamp.setText(myFootprint.getTime());
		// TODO display image from sdcard
		holder.imgLocation.setTag(myFootprint.imagePath);
		imageLoader.displayImage(myFootprint.imagePath, holder.imgLocation);
		
		// listener
		convertView.setOnClickListener(onClickListener);
		
		return convertView;
	}
	
	private MyFootprint myFootprint = null;
	private OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(getContext(), MyFootprintDetailActivity.class);
			intent.putExtra(Global.MY_FOOTPRINT, myFootprint);
			getContext().startActivity(intent);
		}
	};

	static class ViewHolder {
		ImageView imgLocation;
		TextView txtLocationName;
		TextView txtTimestamp; 
	}
}
